# -*- coding: utf-8 -*-
import os
import Models
import time
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from datetime import datetime

class MainPage(webapp.RequestHandler):
    
    def get(self):
        user = GetUser(self)
        self.response.out.write('Hello, ' + user.nickname())
        dataGrid = '<table>'
        gasticsModel = db.GqlQuery("SELECT * FROM GasticsModel WHERE User = :author", author=user)
        for gsModel in gasticsModel:
            dataGrid += ('<tr><td>'
                     +  str(gsModel.Date.strftime('%m-%d-%Y'))
                     + '</td><td>' + str(gsModel.CurrentKilo)
                     + '</td><td>' + str(gsModel.PerCost)
                     + '</td><td>' + str('%.2f'%(gsModel.Price))
                     + '</td><td>' + str('%.2f'%(gsModel.PerVolume))
                     + '</td><td>' + str('%.2f'%(gsModel.AverageGasCost))
                     + '</td><td>' + '<a href="javascript:OnSubmitForm(\'Edit\',\''
                     + str(gsModel.CurrentKilo) + '\');">编辑</a> <a href="javascript:OnSubmitForm(\'Delete\',\''
                     + str(gsModel.CurrentKilo) + '\');">删除</a>'
                     + '</td></tr>')
        dataGrid = '</table>'

        template_values = {'dataGrid': dataGrid}
        
        path = os.path.join(os.path.dirname(__file__), 'debug.html')
        self.response.out.write(template.render(path, template_values))     
        
application = webapp.WSGIApplication([('/', MainPage)],debug=True)

def GetUser(self):
    user = users.get_current_user()
    if user:
        self.response.headers['Content-Type'] = 'text/html'
    else:
        self.redirect(users.create_login_url(self.request.uri))
    return user

def main():
    run_wsgi_app(application)
if __name__ == "__main__":
    main()
